#include <jni.h>
#include <string>
#include "utils.cpp"
#include <vector>

using namespace std;
extern "C"
JNIEXPORT void JNICALL
Java_com_infisense_opencv_ui_home_bitmapdeal_BitmapDealActivity_converImage2Gray(JNIEnv *env,
                                                                                 jobject instance,
                                                                                 jobject bitmap) {
    //源图像
    Mat src;
    //将Bitmap转换为Mat
    BitmapToMat(env, bitmap, src, JNI_FALSE);

    //转换的灰度图
    Mat gray_image;
    cvtColor(src, gray_image, COLOR_BGR2GRAY);

    //将Mat转换为Bitmap
    MatToBitmap(env, gray_image, bitmap, JNI_FALSE);

    //释放Mat
    src.release();
    gray_image.release();
}

/**
 * 加强边缘
 * @param src
 * @param dst
 */
void SobelEnhance(const Mat src, Mat &dst) {
    Mat sobelx(src.size(), CV_16SC1);///边缘检测后，会有负值，也会有大于255的值，因此类型设为CV_16SC1有符号类型
    Mat sobely(src.size(), CV_16SC1);
    Mat img_edgeFiltex(src.size(), CV_8UC1);///结果图，类型设为CV_8UC1进行阈值截断
    Mat img_edgeFiltey(src.size(), CV_8UC1);
    Sobel(src, sobelx, CV_16SC1, 1, 0, 3);
    convertScaleAbs(sobelx, img_edgeFiltex);
    Sobel(src, sobely, CV_16SC1, 0, 1, 3);
    convertScaleAbs(sobely, img_edgeFiltey);
    ///像素加权
    addWeighted(img_edgeFiltex, 1, img_edgeFiltey, 1, 0, dst);
}


extern "C"
JNIEXPORT jobject JNICALL
Java_com_infisense_opencv_ui_home_bitmapdeal_BitmapDealActivity_cropImage(JNIEnv *env,
                                                                          jobject instance,
                                                                          jobject bitmap) {

    //源图像
    Mat src;
    //将Bitmap转换为Mat
    BitmapToMat(env, bitmap, src, JNI_FALSE);

    //加强边缘
    Mat addWeight;
    SobelEnhance(src, addWeight);

    //转换的灰度图
    Mat gray_image;
    cvtColor(addWeight, gray_image, COLOR_BGR2GRAY);

    //图像二值化(去除部分杂质)
    threshold(gray_image, gray_image, 100, 150, THRESH_BINARY);//可以通过调整100和150这两个值来达到自己想要的效果

    //查找外围轮廓
    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;
    Canny(gray_image, gray_image, 100, 300, 3);
    findContours(gray_image, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE,
                 Point(0, 0));//RETR_EXTERNAL为获取外部轮廓
    Rect rect;
    for (size_t i = 0; i < contours.size(); i++) {
        Rect temp = boundingRect(contours[i]);
        //取面积最大的（即为银行卡区域）
        if (temp.width * temp.height > rect.width * rect.height) {
            rect = temp;
            LOGE("轮廓大小:%d,%d", rect.width, rect.height);
        }
    }

    //创建新的Bitmap用于存储裁剪后的图片（由于裁剪前后的图像大小不一样，因此必须创建一个新的Bitmap来存储裁剪后的图像）
    jstring configName = env->NewStringUTF("ARGB_8888");
    jclass bitmapConfigClass = env->FindClass("android/graphics/Bitmap$Config");
    jmethodID valueOfBitmapConfigFunction = env->GetStaticMethodID(bitmapConfigClass, "valueOf",
                                                                   "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;");
    jobject bitmapConfig = env->CallStaticObjectMethod(bitmapConfigClass,
                                                       valueOfBitmapConfigFunction,
                                                       bitmapConfigClass, configName);
    jclass bitmapClazz = env->FindClass("android/graphics/Bitmap");
    jmethodID createBitmapFunction = env->GetStaticMethodID(bitmapClazz, "createBitmap",
                                                            "(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;");
    jobject newBitmap = env->CallStaticObjectMethod(bitmapClazz, createBitmapFunction, rect.width,
                                                    rect.height, bitmapConfig);

    if (rect.width) {
        //依据找到的最大轮廓裁剪源图像
        Mat clipMat(src, rect);
        //将Mat转换为Bitmap
        MatToBitmap(env, clipMat, newBitmap, JNI_FALSE);
        //释放Mat
        src.release();
        gray_image.release();
        clipMat.release();
    } else {
        //释放Mat
        src.release();
        gray_image.release();
    }
    return newBitmap;
}